package com.yeskery.nut.extend.responsive;

import com.yeskery.nut.core.*;
import com.yeskery.nut.plugin.ApplicationContextSupportBasePlugin;
import com.yeskery.nut.plugin.InterceptorPlugin;
import com.yeskery.nut.plugin.PluginBeanMetadata;
import com.yeskery.nut.plugin.PluginBeanMetadataExtender;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 基础响应式处理插件
 * @author sprout
 * 2022-06-08 17:15
 */
public abstract class BaseResponsivePlugin extends ApplicationContextSupportBasePlugin implements InterceptorPlugin {

    /** 响应式接口 */
    private DefaultResponsive responsive;

    /**
     * 获取响应式接口
     * @return 响应式接口
     */
    protected abstract DefaultResponsive getResponsive();

    /**
     * 获取响应式类型名称
     * @return 响应式类型名称
     */
    protected abstract String getTypeName();

    @Override
    protected Collection<PluginBeanMetadata> getRegisterPluginBeanMetadata() {
        responsive = getResponsive();
        ResponsiveConvert responsiveConvert = responsive.getResponsiveConvert();
        List<PluginBeanMetadata> pluginBeanMetadataList = new ArrayList<>(4);
        String typeName = getTypeName();
        pluginBeanMetadataList.add(new PluginBeanMetadata(typeName + "responsive", responsive,
                Responsive.class, responsive.getClass()));
        pluginBeanMetadataList.add(new PluginBeanMetadata(typeName +"responsiveConvert", responsiveConvert,
                ResponsiveConvert.class, Convert.class, responsiveConvert.getClass()));
        if (responsiveConvert instanceof PluginBeanMetadataExtender) {
            Collection<PluginBeanMetadata> pluginBeanMetadataCollection = ((PluginBeanMetadataExtender) responsiveConvert).getExtendPluginBeanMetadata();
            if (!pluginBeanMetadataCollection.isEmpty()) {
                pluginBeanMetadataList.addAll(pluginBeanMetadataCollection);
            }
        }
        return pluginBeanMetadataList;
    }

    @Override
    public boolean beforeHandle(Request request, Response response, Execution execution, Controller controller) throws Exception {
        if (responsive != null) {
            responsive.set(new DefaultResponsive.RequestAndResponse(request, response));
        }
        return true;
    }

    @Override
    public void afterHandle(Request request, Response response, Controller controller, Exception e) throws Exception {
        if (responsive != null) {
            responsive.remove();
        }
    }
}
